<template>
  <view class="my-center-page">
    <!-- 背景纹理图片 - 铺满整个页面 -->
    <view class="page-bg">
      <image src="/static/bg.jpg" mode="aspectFill"></image>
    </view>

    <!-- Profile Section -->
    <view class="profile-section">
      <image class="avatar" :src="userInfo.avatarUrl || '/static/logo.png'" mode="aspectFill"></image>
      <text class="nickname">{{ userInfo.nickname || '未登录' }}</text>

      <!-- 优化后的等级徽章 -->
      <view class="level-badge-new" @click="toggleLevelModal">
        <view class="level-badge-content">
          <view class="level-info-row">
            <view class="level-name-wrapper">
              <text class="level-icon">👑</text>
              <text class="level-name-new">{{ currentLevel ? currentLevel.name : '健康分享者' }}</text>
            </view>
            <view class="commission-badge">
              <text class="commission-rate-new">{{ getCommissionRateText() }}</text>
            </view>
          </view>
          <view class="level-points-row">
            <text class="points-text">当前积分：{{ userInfo.points || 0 }}</text>
            <text class="view-benefits-text">查看权益 ›</text>
          </view>
        </view>
      </view>

      <!-- 升级进度 -->
      <view class="progress-section" v-if="userInfo.nickname && nextLevel">
        <view class="progress-info">
          <text class="next-level-info">{{ upgradeProgress.text }}</text>
        </view>
        <view class="progress-bar-wrapper">
          <view class="progress-bar">
            <view class="progress-fill" :style="{ width: upgradeProgress.percent + '%' }"></view>
          </view>
          <text class="progress-percent">{{ Math.round(upgradeProgress.percent) }}%</text>
        </view>
      </view>
    </view>

    <!-- Commission Section -->
    <view class="commission-section">
      <view class="commission-item">
        <text class="value">{{ formatCurrency(commission_available) }}</text>
        <text class="label">可提现金额 (元)</text>
      </view>
      <view class="commission-item">
        <text class="value">{{ formatCurrency(commission_pending) }}</text>
        <text class="label">待激活 (元)</text>
      </view>
      <view class="commission-item">
        <text class="value">{{ formatCurrency(commission_total) }}</text>
        <text class="label">累计收益 (元)</text>
      </view>
    </view>

    <!-- 优化后的提现按钮 -->
    <view class="withdraw-button-container">
      <button class="withdraw-button-new" @click="withdraw" :disabled="commission_available <= 0">
        <view class="withdraw-button-content">
          <text class="withdraw-icon">💰</text>
          <text class="withdraw-text">立即提现</text>
          <text class="withdraw-amount" v-if="commission_available > 0">¥{{ formatCurrency(commission_available) }}</text>
        </view>
      </button>
    </view>

    <button class="admin-button" v-if="userInfo.isAdmin" @click="goToAdmin">后台管理</button>

    <!-- Order List Section -->
    <view class="orders-section">
      <view class="section-header">
        <view class="tab-bar">
            <view class="tab-item" :class="{active: currentTab === 'buyer'}" @click="changeTab('buyer')">我的购买</view>
            <view class="tab-item" :class="{active: currentTab === 'promoter'}" @click="changeTab('promoter')">我的推广</view>
            <view class="tab-item" :class="{active: currentTab === 'sharing'}" @click="changeTab('sharing')">我的分享</view>
            <view class="tab-item" :class="{active: currentTab === 'points'}" @click="changeTab('points')">积分明细</view>
        </view>

        <!-- 刷新按钮 - 与Tab在同一行 -->
        <view class="refresh-button" @click="refreshCurrentTab" :class="{disabled: isRefreshing}">
          <text class="refresh-icon" :class="{rotating: isRefreshing}">↻</text>
          <text class="refresh-text">刷新</text>
        </view>
      </view>

      <!-- 订单列表内容 - 仅在 buyer/promoter 标签下显示 -->
      <view v-if="currentTab === 'buyer' || currentTab === 'promoter'">
        <view v-if="orders.length === 0" class="empty-orders">
          <text>暂无订单</text>
        </view>
        <view v-else class="order-list">
          <view v-for="order in orders" :key="order._id" class="order-card" @click="openOrderDetail(order)">
            <view class="order-info">
              <text class="order-id">订单号: {{ order._id.slice(-8) }}</text>
              <text class="order-status" :class="order.status">{{ orderStatusText(order.status) }}</text>
            </view>
            <view class="order-details">
              <text>金额: ¥{{ formatCurrency(order.amount) }}</text>
              <text class="order-date">{{ new Date(order.create_time).toLocaleDateString() }}</text>
            </view>

            <!-- 推广订单额外显示返利信息 -->
            <view v-if="currentTab === 'promoter' && order.commission_amount" class="commission-info">
              <view class="commission-row">
                <text class="commission-label">返利金额:</text>
                <text class="commission-amount">¥{{ formatCurrency(order.commission_amount) }}</text>
              </view>
              <view class="commission-row">
                <text class="commission-label">返利状态:</text>
                <text class="commission-status-tag" :class="getCommissionStatusClass(order)">
                  {{ getCommissionStatusText(order) }}
                </text>
              </view>
              <!-- 显示激活倒计时：只有订单已完成且佣金待激活时才显示 -->
              <view v-if="order.status === 'completed' && order.commission_status === 'pending' && getActivationDaysRemaining(order) > 0" class="activation-countdown">
                <text class="countdown-icon">⏱</text>
                <text class="countdown-text">{{ getActivationDaysRemaining(order) }}天后可提现</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 我的分享内容 - 仅在 sharing 标签下显示 -->
      <view v-if="currentTab === 'sharing'" class="sharing-content">
        <!-- 分享统计摘要 -->
        <view class="sharing-summary">
          <view class="summary-item">
            <text class="summary-number">{{ sharingSummary.totalUsers }}</text>
            <text class="summary-label">推广用户</text>
          </view>
          <view class="summary-item">
            <text class="summary-number">{{ sharingSummary.purchasedUsers }}</text>
            <text class="summary-label">已购买</text>
          </view>
          <view class="summary-item">
            <text class="summary-number">¥{{ formatCurrency(sharingSummary.totalCommission) }}</text>
            <text class="summary-label">获得佣金</text>
          </view>
        </view>

        <!-- 分享用户列表 -->
        <view v-if="sharingUsers.length === 0" class="empty-sharing">
          <text>暂无推广用户</text>
          <text class="empty-tip">分享商品给好友，邀请他们注册即可获得积分奖励</text>
        </view>
        <view v-else class="sharing-list">
          <view v-for="user in sharingUsers" :key="user._id" class="sharing-card">
            <view class="user-avatar">
              <image :src="user.avatar || user.avatarUrl || '/static/logo.png'" mode="aspectFill"></image>
            </view>
            <view class="user-info">
              <text class="user-nickname">{{ user.nickname || '匿名用户' }}</text>
              <text class="user-register-time">注册时间: {{ formatDate(user.registerTime || user.register_date) }}</text>
              <view class="user-status">
                <text class="status-tag" :class="user.hasPurchased ? 'purchased' : 'not-purchased'">
                  {{ user.hasPurchased ? '已购买' : '未购买' }}
                </text>
                <text v-if="user.totalCommission > 0" class="commission-tag">
                  佣金: ¥{{ formatCurrency(user.totalCommission) }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 积分明细内容 - 仅在 points 标签下显示 -->
      <view v-if="currentTab === 'points'" class="points-content">
        <!-- 积分统计摘要 -->
        <view class="points-summary">
          <view class="summary-card">
            <text class="summary-title">当前积分</text>
            <text class="summary-value">{{ userInfo.points || 0 }}</text>
          </view>
        </view>

        <!-- 积分记录列表 -->
        <view v-if="pointRecords.length === 0 && !isLoadingPoints" class="empty-points">
          <text class="empty-icon">📊</text>
          <text class="empty-text">暂无积分记录</text>
          <text class="empty-tip">完成订单或推荐好友即可获得积分</text>
        </view>

        <view v-else class="points-list">
          <view v-for="record in pointRecords" :key="record._id" class="point-record-card">
            <view class="record-header">
              <view class="record-left">
                <text class="record-icon">{{ getPointRecordIcon(record.change_type) }}</text>
                <view class="record-info">
                  <text class="record-description">{{ record.description }}</text>
                  <text class="record-time">{{ formatRecordTime(record.create_time) }}</text>
                </view>
              </view>
              <view class="record-right">
                <text class="record-amount" :class="record.change_amount > 0 ? 'positive' : 'negative'">
                  {{ record.change_amount > 0 ? '+' : '' }}{{ record.change_amount }}
                </text>
                <text class="record-balance">余额: {{ record.balance_after }}</text>
              </view>
            </view>
          </view>

          <!-- 加载更多 -->
          <view v-if="hasMorePoints" class="load-more" @click="loadMorePoints">
            <text class="load-more-text">{{ isLoadingPoints ? '加载中...' : '加载更多' }}</text>
          </view>
          <view v-else-if="pointRecords.length > 0" class="no-more">
            <text class="no-more-text">没有更多记录了</text>
          </view>
        </view>
      </view>
    </view>

    <!-- Level Modal -->
    <view class="level-modal" v-if="showLevelModal" @click="toggleLevelModal">
      <view class="modal-content" @click.stop>
        <text class="modal-title">等级权益说明</text>
        <view class="guidance-section">
          <text class="guidance-title">成长路径</text>
          <text class="guidance-text">通过分享商品链接，邀请好友购买，即可获得积分和佣金，开启您的成长之旅！</text>
        </view>
        <view class="level-list">
          <view v-for="level in levelSystem" :key="level.name" class="level-item" :class="{active: currentLevel && level.name === currentLevel.name}">
            <view class="level-header">
              <text class="level-name-modal">{{ level.name }}</text>
              <text class="level-status" v-if="currentLevel && level.name === currentLevel.name">当前等级</text>
            </view>
            <view class="level-requirements">
              <text class="points-range">积分要求：{{ level.pointsRange }}</text>
              <text class="commission-rate">佣金比例：{{ getLevelCommissionRate(level.name) }}</text>
              <text class="special-benefit" v-if="level.specialBenefit">{{ level.specialBenefit }}</text>
            </view>
          </view>
        </view>
        <button class="close-button" @click="toggleLevelModal">关闭</button>
      </view>
    </view>

    <!-- Withdraw Modal -->
    <view class="withdraw-modal" v-if="showWithdrawModal" @click="closeWithdrawModal">
      <view class="withdraw-modal-content" @click.stop>
        <text class="withdraw-modal-title">提现金额</text>
        <text class="withdraw-modal-subtitle">可提现金额：¥{{ formatCurrency(commission_available) }}</text>

        <view class="withdraw-input-group">
          <text class="withdraw-label">请输入提现金额（元）</text>
          <view class="withdraw-input-wrapper">
            <text class="currency-symbol">¥</text>
            <input
              v-model="withdrawAmount"
              type="number"
              placeholder="输入金额，最小1元，最大200元"
              class="withdraw-input"
              @input="validateWithdrawAmount"
            />
          </view>
          <text class="withdraw-tips">最小提现金额：¥1.00 | 最大提现金额：¥200.00</text>
        </view>

        <view v-if="withdrawError" class="withdraw-error">
          <text>{{ withdrawError }}</text>
        </view>

        <view class="withdraw-button-group">
          <button class="withdraw-cancel-button" @click="closeWithdrawModal">取消</button>
          <button class="withdraw-confirm-button" @click="confirmWithdraw">确认提现</button>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {},
      justLoggedIn: false,
      commission_total: 0,
      commission_pending: 0,
      commission_available: 0,
      orders: [],
      currentTab: 'buyer', // buyer, promoter or sharing
      isSyncing: false,
      isRefreshing: false,
      // 分页相关
      currentPage: 1,
      pageSize: 50, // 每页加载50条订单
      totalOrders: 0,
      // 我的分享数据
      sharingUsers: [],
      totalSharingUsers: 0,
      sharingSummary: {
        totalUsers: 0,
        purchasedUsers: 0,
        totalCommission: 0
      },
      // 积分明细数据
      pointRecords: [],
      pointRecordsPage: 1,
      pointRecordsPageSize: 20,
      totalPointRecords: 0,
      hasMorePoints: false,
      isLoadingPoints: false,

      showLevelModal: false,
      // 提现弹窗相关
      showWithdrawModal: false,
      withdrawAmount: '',
      withdrawError: '',
      // 动态的等级体系定义（从数据库获取）
      levelSystem: [],
      // 佣金规则配置（从数据库获取）
      commissionRules: null
    };
  },
  computed: {
    currentLevel() {
      // 如果等级体系未加载，返回 null
      if (!this.levelSystem || this.levelSystem.length === 0) {
        return null;
      }

      const currentPoints = this.userInfo.points || 0;
      // 从高到低查找，找到第一个满足条件的等级
      for (let i = this.levelSystem.length - 1; i >= 0; i--) {
        if (currentPoints >= this.levelSystem[i].pointsRequired) {
          return this.levelSystem[i];
        }
      }
      return this.levelSystem[0]; // 默认返回健康分享者
    },
    nextLevel() {
      // 如果等级体系未加载，返回 null
      if (!this.levelSystem || this.levelSystem.length === 0) {
        return null;
      }

      const currentPoints = this.userInfo.points || 0;
      // 找到下一个等级
      for (let i = 0; i < this.levelSystem.length; i++) {
        if (currentPoints < this.levelSystem[i].pointsRequired) {
          return this.levelSystem[i];
        }
      }
      return null; // 已经是最高等级
    },
    upgradeProgress() {
      const currentPoints = this.userInfo.points || 0;
      
      if (!this.nextLevel) {
        return { 
          percent: 100, 
          text: '恭喜！您已达到最高等级 - 区域代理' 
        };
      }
      
      const currentLevelStart = this.currentLevel.pointsRequired;
      const nextLevelStart = this.nextLevel.pointsRequired;
      const pointsToNext = nextLevelStart - currentPoints;
      
      // 计算当前等级内的进度
      const rangeSize = nextLevelStart - currentLevelStart;
      const progressInRange = currentPoints - currentLevelStart;
      const percent = rangeSize > 0 ? (progressInRange / rangeSize) * 100 : 0;
      
      return {
        percent: Math.max(0, Math.min(percent, 100)),
        text: `再获得 ${pointsToNext} 积分即可升级为 ${this.nextLevel.name}`
      };
    }
  },
  onLoad() {
    // 立即从本地存储恢复用户信息，避免显示"未登录"
    const userInfo = uni.getStorageSync('userInfo');

    if (userInfo) {
      this.userInfo = userInfo;
      this.commission_total = userInfo.commission_total || 0;
      this.commission_pending = userInfo.commission_pending || 0;
      this.commission_available = userInfo.commission_available || 0;
    }

    // 加载佣金规则配置（用于等级权益说明）
    this.loadCommissionRules();

    // 监听登录成功事件，避免 onShow 的重复请求
    uni.$on('userLoggedIn', (loggedInUser) => {
      this.userInfo = loggedInUser;
      this.commission_total = loggedInUser.commission_total || 0;
      this.commission_pending = loggedInUser.commission_pending || 0;
      this.commission_available = loggedInUser.commission_available || 0;
      this.justLoggedIn = true;
      this.fetchPageData();
    });

    // 监听订单同步成功事件
    uni.$on('ordersUpdated', () => {
      console.log('接收到订单更新事件，刷新页面数据');
      this.fetchPageData();
    });
  },
  onShow() {
    if (this.justLoggedIn) {
      this.justLoggedIn = false;
      return;
    }

    // 保持当前tab状态，不强制重置为buyer
    if (this.currentTab === 'sharing') {
      this.fetchSharingData();
    } else {
      this.fetchPageData();
    }
  },
  methods: {
    /**
     * 加载佣金规则配置
     * 从数据库获取最新的佣金规则，并动态生成等级体系
     */
    async loadCommissionRules() {
      try {
        const res = await uniCloud.callFunction({
          name: 'admin-center',
          data: { action: 'getRules' }
        });

        if (res.result && res.result.code === 0 && res.result.data) {
          const rulesData = res.result.data;

          // 保存佣金规则配置
          if (rulesData.commission_rules) {
            this.commissionRules = rulesData.commission_rules;

            // 根据佣金规则动态生成等级体系
            if (rulesData.commission_rules.levels && Array.isArray(rulesData.commission_rules.levels)) {
              this.levelSystem = this.generateLevelSystem(rulesData.commission_rules.levels);
              console.log('[等级体系] 已从数据库加载:', this.levelSystem);
            }
          }
        }
      } catch (error) {
        console.error('[加载佣金规则失败]', error);
        // 如果加载失败，使用默认配置
        this.initDefaultLevelSystem();
      }
    },

    /**
     * 根据佣金规则生成等级体系
     * @param {Array} levels - 佣金规则中的等级配置
     * @returns {Array} 等级体系数组
     */
    generateLevelSystem(levels) {
      // 按积分要求排序
      const sortedLevels = [...levels].sort((a, b) => a.points_required - b.points_required);

      return sortedLevels.map((level, index) => {
        const nextLevel = sortedLevels[index + 1];
        const maxPoints = nextLevel ? nextLevel.points_required - 1 : Infinity;

        // 生成积分范围文本
        let pointsRange;
        if (maxPoints === Infinity) {
          pointsRange = `${level.points_required}分以上`;
        } else {
          pointsRange = `${level.points_required}-${maxPoints}分`;
        }

        return {
          name: level.name,
          pointsRange: pointsRange,
          pointsRequired: level.points_required,
          maxPoints: maxPoints,
          commissionRate: level.commission_rate, // 保存原始比例（0-1之间）
          specialBenefit: level.name === '区域代理' ? '享受团队业绩奖：成交金额超过1000元奖励5%' : null
        };
      });
    },

    /**
     * 初始化默认等级体系（当数据库加载失败时使用）
     */
    initDefaultLevelSystem() {
      console.warn('[等级体系] 使用默认配置');
      this.levelSystem = [
        {
          name: '健康分享者',
          pointsRange: '0-100分',
          pointsRequired: 0,
          maxPoints: 100,
          commissionRate: 0.10,
          specialBenefit: null
        },
        {
          name: '推广大使',
          pointsRange: '101-500分',
          pointsRequired: 101,
          maxPoints: 500,
          commissionRate: 0.12,
          specialBenefit: null
        },
        {
          name: '区域代理',
          pointsRange: '501分以上',
          pointsRequired: 501,
          maxPoints: Infinity,
          commissionRate: 0.15,
          specialBenefit: '享受团队业绩奖：成交金额超过1000元奖励5%'
        }
      ];
    },

    orderStatusText(status) {
      const map = {
        unpaid: '待付款',
        paid: '待发货',
        shipped: '待收货',
        completed: '已完成',
        cancelled: '已取消',
        refunded: '已退款'
      };
      return map[status] || status;
    },
    goToAdmin() {
      uni.navigateTo({ url: '/pages/admin/admin' });
    },
    toggleLevelModal() {
      this.showLevelModal = !this.showLevelModal;
      // 每次打开弹窗时重新加载佣金规则，确保显示最新数据
      if (this.showLevelModal) {
        this.loadCommissionRules();
      }
    },
    /**
     * 获取用户信息（独立方法，可被其他方法调用）
     */
    async fetchUserInfo() {
      const token = uni.getStorageSync('uni_id_token');
      if (!token) {
        return;
      }

      try {
        const userRes = await uniCloud.callFunction({
          name: 'user-center',
          data: { action: 'getUserInfo' }
        });

        if (userRes.result && userRes.result.code === 0) {
          const userInfo = userRes.result.userInfo;
          this.userInfo = userInfo;
          this.commission_total = userInfo.commission_total || 0;
          this.commission_pending = userInfo.commission_pending || 0;
          this.commission_available = userInfo.commission_available || 0;
          uni.setStorageSync('userInfo', userInfo);
          console.log('[用户信息] 已更新，当前积分:', userInfo.points);
        } else {
          console.error('[用户信息] 获取失败:', userRes.result?.message);
        }
      } catch (error) {
        console.error('[用户信息] 获取异常:', error);
      }
    },

    async fetchPageData() {
      const token = uni.getStorageSync('uni_id_token');
      if (!token) {
        this.userInfo = {};
        this.commission_total = 0;
        this.commission_pending = 0;
        this.commission_available = 0;
        this.orders = [];
        uni.removeStorageSync('userInfo');
        uni.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '加载中...' });
      try {
        // 异步后台同步订单（不阻塞页面加载）
        console.log('[AUTO-SYNC] 启动后台订单同步任务...');
        this.syncOrdersInBackground();

        // 立即获取用户信息和订单列表（不等待同步完成）
        const [userRes, orderRes] = await Promise.all([
          uniCloud.callFunction({ name: 'user-center', data: { action: 'getUserInfo' } }),
          uniCloud.callFunction({ name: 'order-center', data: { action: 'getOrders' } })
        ]);

        if (userRes.result && userRes.result.code === 0) {
          const userInfo = userRes.result.userInfo;
          this.userInfo = userInfo;
          this.commission_total = userInfo.commission_total || 0;
          this.commission_pending = userInfo.commission_pending || 0;
          this.commission_available = userInfo.commission_available || 0;
          uni.setStorageSync('userInfo', userInfo);
        } else {
          throw new Error(userRes.result.message || '获取用户信息失败');
        }

        if (orderRes.result && orderRes.result.code === 0) {
          this.orders = orderRes.result.data;
        } else {
          console.warn('获取订单失败:', orderRes.result.message);
        }

        // 使用固定的等级配置，无需从后端获取

        // 如果当前在分享标签页，也加载分享数据
        if (this.currentTab === 'sharing') {
          await this.fetchSharingData();
        }

      } catch (error) {
        if (error.message && (error.message.includes('token') || error.message.includes('登录') || error.message.includes('TOKEN'))) {
          this.userInfo = {};
          this.commission_total = 0;
          this.commission_pending = 0;
          this.commission_available = 0;
          this.orders = [];
          uni.removeStorageSync('userInfo');
          uni.removeStorageSync('uni_id_token');
          uni.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
        } else {
          uni.showToast({ title: `错误: ${error.message}`, icon: 'none' });
        }
      } finally {
        uni.hideLoading();
      }
    },
    async confirmOrder(orderId) {
      uni.showLoading({ title: '确认中...' });
      try {
        const res = await uniCloud.callFunction({
          name: 'order-center',
          data: {
            action: 'completeOrder',
            params: { orderId }
          }
        });
        if (res.result && res.result.code === 0) {
          uni.showToast({ title: '操作成功！佣金已激活', icon: 'success' });
          this.fetchPageData();
        } else {
          throw new Error(res.result.message || '操作失败');
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({ title: `错误: ${error.message}`, icon: 'none' });
      }
    },
    withdraw() {
      if (!this.commission_available || this.commission_available <= 0) {
        uni.showToast({ title: '没有可提现的金额', icon: 'none' });
        return;
      }
      // 打开提现弹窗
      this.showWithdrawModal = true;
      this.withdrawAmount = '';
      this.withdrawError = '';
    },
    validateWithdrawAmount() {
      const amount = parseFloat(this.withdrawAmount);
      this.withdrawError = '';

      // 检查是否为空
      if (!this.withdrawAmount || this.withdrawAmount.trim() === '') {
        this.withdrawError = '请输入提现金额';
        return false;
      }

      // 检查是否为有效数字
      if (isNaN(amount)) {
        this.withdrawError = '请输入有效的数字';
        return false;
      }

      // 检查最小金额（大于1元）
      if (amount <= 1) {
        this.withdrawError = '最小提现金额需要大于1元';
        return false;
      }

      // 检查最大金额（不超过200元）
      if (amount > 200) {
        this.withdrawError = '单次提现金额不能超过200元';
        return false;
      }

      // 检查不超过可提现金额
      const availableAmount = this.commission_available / 100; // 转换为元
      if (amount > availableAmount) {
        this.withdrawError = `可提现金额为 ¥${this.formatCurrency(this.commission_available)}，不能超过此金额`;
        return false;
      }

      return true;
    },
    async confirmWithdraw() {
      if (!this.validateWithdrawAmount()) {
        return;
      }

      const amountToWithdraw = Math.round(parseFloat(this.withdrawAmount) * 100); // 转换为分

      const modalRes = await uni.showModal({
        title: '提现确认',
        content: `您确定要提现 ¥${this.withdrawAmount} 吗？`
      });

      if (modalRes.confirm) {
        this.showWithdrawModal = false;
        uni.showLoading({ title: '正在处理...' });
        try {
          // 第一步：调用后端生成转账package
          console.log('[提现] 开始生成转账package...');
          const packageRes = await uniCloud.callFunction({
            name: 'user-center',
            data: {
              action: 'generateTransferPackage',
              params: { amount: amountToWithdraw }
            }
          });

          if (!packageRes.result || packageRes.result.code !== 0) {
            throw new Error(packageRes.result?.message || '生成package失败');
          }

          const packageData = packageRes.result.data;
          console.log('[提现] Package生成成功:', {
            mchId: packageData.mchId,
            appId: packageData.appId,
            outBillNo: packageData.outBillNo
          });

          // 第二步：检查微信API可用性
          uni.hideLoading();
          if (!wx.canIUse('requestMerchantTransfer')) {
            uni.showModal({
              title: '提示',
              content: '你的微信版本过低，请更新至最新版本后重试',
              showCancel: false
            });
            return;
          }

          // 第三步：调用微信转账API
          console.log('[提现] 调用wx.requestMerchantTransfer()...');
          uni.showLoading({ title: '请在微信官方页面确认...' });

          wx.requestMerchantTransfer({
            mchId: packageData.mchId,
            appId: packageData.appId,
            package: packageData.package,
            success: (res) => {
              console.log('[提现] 用户确认成功:', res);
              uni.hideLoading();
              uni.showToast({
                title: '提现已提交，请等待处理',
                icon: 'success'
              });
              // 立即刷新页面数据，显示已扣除的余额
              setTimeout(() => {
                this.fetchPageData();
              }, 1000);
            },
            fail: (res) => {
              console.error('[提现] 用户取消或失败:', res);
              uni.hideLoading();

              // 如果用户取消，需要回滚余额
              if (res.errMsg && res.errMsg.includes('cancel')) {
                console.log('[提现] 用户取消提现，需要回滚余额');
                uni.showToast({
                  title: '提现已取消，余额已退回',
                  icon: 'none'
                });
                // 延迟刷新，让用户看到余额恢复
                setTimeout(() => {
                  this.fetchPageData();
                }, 1000);
              } else {
                uni.showToast({
                  title: `提现失败: ${res.errMsg || '未知错误'}`,
                  icon: 'none'
                });
              }
            }
          });

        } catch (error) {
          uni.hideLoading();
          console.error('[提现] 错误:', error);
          uni.showToast({ title: `错误: ${error.message}`, icon: 'none' });
        }
      }
    },
    closeWithdrawModal() {
      this.showWithdrawModal = false;
      this.withdrawAmount = '';
      this.withdrawError = '';
    },
    formatCurrency(amountInCents) {
      if (typeof amountInCents !== 'number' || !amountInCents) {
        return '0.00';
      }
      return (amountInCents / 100).toFixed(2);
    },
    /**
     * 获取当前用户的佣金比例文本
     * 根据用户积分动态计算对应的佣金比例
     * @returns {string} 佣金比例文本，如 "25%"
     */
    getCommissionRateText() {
      const currentPoints = this.userInfo.points || 0;

      // 如果等级体系未加载，返回默认值
      if (!this.levelSystem || this.levelSystem.length === 0) {
        return '10%';
      }

      // 从高到低查找匹配的等级
      for (let i = this.levelSystem.length - 1; i >= 0; i--) {
        const level = this.levelSystem[i];
        if (currentPoints >= level.pointsRequired) {
          // 将小数转换为百分比文本
          return `${Math.round(level.commissionRate * 100)}%`;
        }
      }

      // 默认返回第一个等级的佣金比例
      return `${Math.round(this.levelSystem[0].commissionRate * 100)}%`;
    },

    /**
     * 根据等级名称获取佣金比例文本
     * 用于等级权益说明弹窗中显示各等级的佣金比例
     * @param {string} levelName - 等级名称
     * @returns {string} 佣金比例文本，如 "25%"
     */
    getLevelCommissionRate(levelName) {
      // 如果等级体系未加载，返回默认值
      if (!this.levelSystem || this.levelSystem.length === 0) {
        return '10%';
      }

      // 查找对应等级
      const level = this.levelSystem.find(l => l.name === levelName);
      if (level && level.commissionRate) {
        // 将小数转换为百分比文本
        return `${Math.round(level.commissionRate * 100)}%`;
      }

      // 默认返回 10%
      return '10%';
    },

    /**
     * 获取订单的返利状态文本
     * @param {Object} order - 订单对象
     * @returns {string} 返利状态文本
     */
    getCommissionStatusText(order) {
      // 如果没有返利金额，返回"无返利"
      if (!order.commission_amount || order.commission_amount <= 0) {
        return '无返利';
      }

      // 根据返利状态返回对应文本
      switch (order.commission_status) {
        case 'pending':
          return '待激活';
        case 'activated':
          return '已激活';
        case 'cancelled':
          return '已失效';
        default:
          return '未知状态';
      }
    },

    /**
     * 获取订单返利状态的样式类名
     * @param {Object} order - 订单对象
     * @returns {string} CSS类名
     */
    getCommissionStatusClass(order) {
      if (!order.commission_amount || order.commission_amount <= 0) {
        return 'status-none';
      }

      switch (order.commission_status) {
        case 'pending':
          return 'status-pending';
        case 'activated':
          return 'status-activated';
        case 'cancelled':
          return 'status-cancelled';
        default:
          return 'status-unknown';
      }
    },

    /**
     * 动态计算激活剩余天数
     * 根据 activation_date 和当前时间实时计算
     * @param {Object} order - 订单对象
     * @returns {number} 剩余天数（向上取整）
     */
    getActivationDaysRemaining(order) {
      // 如果没有激活日期，返回数据库中的 activation_countdown 字段（兜底）
      if (!order.activation_date) {
        return order.activation_countdown || 0;
      }

      // 计算当前时间距离激活日期的毫秒数
      const now = Date.now();
      const activationDate = order.activation_date;
      const timeDiff = activationDate - now;

      // 如果激活日期已到或已过，返回 0
      if (timeDiff <= 0) {
        return 0;
      }

      // 将毫秒转换为天数，向上取整
      const daysRemaining = Math.ceil(timeDiff / (24 * 60 * 60 * 1000));
      return daysRemaining;
    },
    formatDate(timestamp) {
      if (!timestamp) return '未知时间';
      try {
        const date = new Date(timestamp);
        return date.toLocaleDateString('zh-CN');
      } catch (e) {
        return '未知时间';
      }
    },
    changeTab(tab) {
        if (this.currentTab === tab) return;
        this.currentTab = tab;

        // Clear data based on tab type
        if (tab === 'sharing') {
            this.sharingUsers = [];
            this.fetchSharingData();
            // 刷新用户信息以更新积分显示
            this.fetchUserInfo();
        } else if (tab === 'points') {
            this.pointRecords = [];
            this.pointRecordsPage = 1;
            this.fetchPointRecords();
            // 刷新用户信息以更新积分显示
            this.fetchUserInfo();
        } else {
            this.orders = []; // Clear old list before fetching new one
            this.currentPage = 1; // 重置页码
            this.fetchOrders();
        }
    },
    async fetchOrders() {
        if (!uni.getStorageSync('uni_id_token')) {
            console.log('[FETCH] 未登录，跳过获取订单');
            return;
        }

        console.log('[FETCH] 开始获取订单，类型:', this.currentTab, '页码:', this.currentPage);
        uni.showLoading({ title: '加载订单...' });
        try {
            const orderRes = await uniCloud.callFunction({
                name: 'order-center',
                data: {
                    action: 'getOrders',
                    params: {
                        type: this.currentTab,
                        page: this.currentPage,
                        pageSize: this.pageSize
                    }
                }
            });
            console.log('[FETCH] 云函数返回:', orderRes);
            console.log('[FETCH] result:', orderRes.result);

            if (orderRes.result.code === 0) {
                console.log('[FETCH] 获取到订单数量:', orderRes.result.data.length);
                console.log('[FETCH] 总订单数:', orderRes.result.total);
                console.log('[FETCH] 订单数据:', orderRes.result.data);
                this.orders = orderRes.result.data;
                this.totalOrders = orderRes.result.total || 0;
            } else {
                console.error('[FETCH] 获取订单失败:', orderRes.result.message);
                throw new Error(orderRes.result.message);
            }
        } catch (e) {
            console.error('[FETCH] 获取订单异常:', e);
            uni.showToast({ title: e.message || '订单加载失败', icon: 'none' });
        } finally {
            uni.hideLoading();
        }
    },

    openOrderDetail(order) {
        if (wx.openStoreOrderDetail) {
            wx.openStoreOrderDetail({ orderId: order._id });
        } else {
            uni.showModal({
                title: '订单详情',
                content: `订单号: ${order._id}\n金额: ${this.formatCurrency(order.amount)}元`,
                showCancel: false
            });
        }
    },

    async syncOrdersInBackground() {
        // 后台异步同步订单，不阻塞页面加载
        try {
            console.log('[AUTO-SYNC] 启动后台异步同步...');

            // 使用异步版本，立即返回，后台处理
            const res = await uniCloud.callFunction({
                name: 'order-center',
                data: { action: 'syncWechatOrdersAsync' }
            });

            if (res.result && res.result.code === 0) {
                console.log('[AUTO-SYNC] 后台同步已启动:', res.result.message);
                // 异步同步已启动，不需要等待
                // 5秒后检查是否有新订单
                setTimeout(() => {
                    console.log('[AUTO-SYNC] 5秒后检查订单更新...');
                    this.fetchOrders();
                }, 5000);
            } else {
                console.warn('[AUTO-SYNC] 启动后台同步失败:', res.result?.message);
            }
        } catch (err) {
            console.warn('[AUTO-SYNC] 启动后台同步异常:', err.message);
            // 后台同步失败不影响用户体验
        }
    },

    async fetchSharingData() {
      if (!uni.getStorageSync('uni_id_token')) {
        console.log('[SHARING] 未登录，跳过获取分享数据');
        return;
      }

      console.log('[SHARING] 开始获取分享用户数据');
      uni.showLoading({ title: '加载中...' });

      try {
        const res = await uniCloud.callFunction({
          name: 'user-center',
          data: {
            action: 'getMySharingUsers'
          }
        });

        console.log('[SHARING] 云函数返回:', res);

        if (res.result && res.result.code === 0) {
          this.sharingUsers = res.result.data || [];
          this.totalSharingUsers = res.result.total || 0;
          this.sharingSummary = res.result.summary || {
            totalUsers: 0,
            purchasedUsers: 0,
            totalCommission: 0
          };
          console.log('[SHARING] 获取到分享用户数量:', this.sharingUsers.length);
        } else {
          console.error('[SHARING] 获取分享用户失败:', res.result?.message);
          throw new Error(res.result?.message || '获取分享用户失败');
        }
      } catch (error) {
        console.error('[SHARING] 获取分享用户异常:', error);
        uni.showToast({ title: error.message || '分享用户加载失败', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },

    /**
     * 获取积分明细记录
     */
    async fetchPointRecords() {
      if (!uni.getStorageSync('uni_id_token')) {
        console.log('[积分明细] 未登录，跳过获取');
        return;
      }

      if (this.isLoadingPoints) {
        console.log('[积分明细] 正在加载中，跳过');
        return;
      }

      console.log('[积分明细] 开始获取，页码:', this.pointRecordsPage);
      this.isLoadingPoints = true;

      try {
        const res = await uniCloud.callFunction({
          name: 'user-center',
          data: {
            action: 'getPointRecords',
            params: {
              page: this.pointRecordsPage,
              pageSize: this.pointRecordsPageSize
            }
          }
        });

        console.log('[积分明细] 云函数返回:', res);

        if (res.result && res.result.code === 0) {
          const { records, total, hasMore } = res.result.data;
          this.pointRecords = [...this.pointRecords, ...records];
          this.totalPointRecords = total;
          this.hasMorePoints = hasMore;
          console.log('[积分明细] 获取到记录数量:', records.length, '总数:', total);
        } else {
          console.error('[积分明细] 获取失败:', res.result?.message);
          throw new Error(res.result?.message || '获取积分明细失败');
        }
      } catch (error) {
        console.error('[积分明细] 获取异常:', error);
        uni.showToast({ title: error.message || '积分明细加载失败', icon: 'none' });
      } finally {
        this.isLoadingPoints = false;
      }
    },

    /**
     * 加载更多积分记录
     */
    async loadMorePoints() {
      if (this.isLoadingPoints || !this.hasMorePoints) {
        return;
      }
      this.pointRecordsPage++;
      await this.fetchPointRecords();
    },

    /**
     * 获取积分记录图标
     */
    getPointRecordIcon(changeType) {
      const iconMap = {
        'referral_register': '👥',
        'purchase_complete': '🛍️',
        'promotion_complete': '🎁',
        'order_cancel': '❌',
        'order_refund': '↩️',
        'manual_adjust': '✏️',
        'system_adjust': '⚙️'
      };
      return iconMap[changeType] || '📝';
    },

    /**
     * 格式化记录时间
     */
    formatRecordTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const now = new Date();
      const diff = now - date;

      // 1分钟内
      if (diff < 60000) {
        return '刚刚';
      }
      // 1小时内
      if (diff < 3600000) {
        return `${Math.floor(diff / 60000)}分钟前`;
      }
      // 今天
      if (date.toDateString() === now.toDateString()) {
        return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      }
      // 昨天
      const yesterday = new Date(now);
      yesterday.setDate(yesterday.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      }
      // 其他
      return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },

    async refreshCurrentTab() {
      if (this.isRefreshing) {
        return;
      }

      this.isRefreshing = true;

      try {
        if (this.currentTab === 'sharing') {
          console.log('[刷新] 刷新分享用户数据');
          // 同时刷新用户信息和分享数据
          await Promise.all([
            this.fetchUserInfo(),
            this.fetchSharingData()
          ]);
          uni.showToast({
            title: '分享用户数据已更新',
            icon: 'success',
            duration: 1500
          });
        } else if (this.currentTab === 'points') {
          console.log('[刷新] 刷新积分明细数据');
          this.pointRecords = [];
          this.pointRecordsPage = 1;
          // 同时刷新用户信息和积分明细
          await Promise.all([
            this.fetchUserInfo(),
            this.fetchPointRecords()
          ]);
          uni.showToast({
            title: '积分明细已更新',
            icon: 'success',
            duration: 1500
          });
        } else {
          // 原有的订单刷新逻辑
          await this.refreshOrderStatus();
        }
      } catch (error) {
        console.error('[刷新] 失败:', error);
        uni.showToast({
          title: error.message || '刷新失败',
          icon: 'none'
        });
      } finally {
        this.isRefreshing = false;
      }
    },

    async refreshOrderStatus() {
        if (this.isRefreshing) {
            return;
        }

        this.isRefreshing = true;
        console.log('[刷新订单] 开始刷新订单状态...');

        try {
            uni.showLoading({ title: '刷新中...' });

            // 调用云函数刷新当前用户的订单状态
            const res = await uniCloud.callFunction({
                name: 'order-center',
                data: {
                    action: 'refreshUserOrders'
                }
            });

            console.log('[刷新订单] 云函数返回:', res);

            if (res.result.code === 0) {
                const { updatedCount } = res.result.data;

                // 刷新订单列表
                await this.fetchOrders();

                // 同时刷新用户信息（佣金和积分可能有变化）
                try {
                    const userRes = await uniCloud.callFunction({
                        name: 'user-center',
                        data: { action: 'getUserInfo' }
                    });

                    if (userRes.result && userRes.result.code === 0) {
                        // getUserInfo 返回的是 userInfo 字段，不是 data 字段
                        const userData = userRes.result.userInfo || userRes.result.data;
                        if (userData) {
                            this.userInfo = userData;
                            this.commission_total = userData.commission_total || 0;
                            this.commission_pending = userData.commission_pending || 0;
                            this.commission_available = userData.commission_available || 0;
                            uni.setStorageSync('userInfo', userData);
                        }
                    }
                } catch (userError) {
                    console.error('[刷新订单] 刷新用户信息失败:', userError);
                    // 用户信息刷新失败不影响订单刷新结果
                }

                // 显示刷新结果
                if (updatedCount > 0) {
                    uni.showToast({
                        title: `已更新 ${updatedCount} 条订单`,
                        icon: 'success',
                        duration: 2000
                    });
                } else {
                    uni.showToast({
                        title: '订单状态已是最新',
                        icon: 'none',
                        duration: 1500
                    });
                }

            } else {
                throw new Error(res.result.message || '刷新失败');
            }

        } catch (error) {
            console.error('[刷新订单] 失败:', error);
            uni.showToast({
                title: error.message || '刷新失败',
                icon: 'none'
            });
        } finally {
            uni.hideLoading();
            this.isRefreshing = false;
        }
    }
  },
  onUnload() {
    uni.$off('userLoggedIn');
    uni.$off('ordersUpdated');
  }
};
</script>

<style>
.my-center-page {
  background: linear-gradient(180deg, #f8fdf8 0%, #ffffff 100%);
  min-height: 100vh;
  padding-bottom: 40rpx;
  position: relative;
}

/* 背景纹理层 - 铺满整个页面 */
.page-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
}

.page-bg image {
  width: 100%;
  height: 100%;
  /* 使用混合模式增强纹理效果 */
  mix-blend-mode: multiply;
  opacity: 0.05;
}

.profile-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
  background: linear-gradient(135deg, #4a5d23 0%, #5a6d33 100%);
  color: white;
  position: relative;
  z-index: 2;
}

.avatar {
  width: 150rpx;
  height: 150rpx;
  border-radius: 50%;
  border: 4rpx solid white;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.nickname {
  font-size: 36rpx;
  font-weight: bold;
}

/* 旧版等级徽章样式（保留以防兼容） */
.level-badge {
  background-color: rgba(255,255,255,0.2);
  padding: 12rpx 24rpx;
  border-radius: 30rpx;
  margin-top: 20rpx;
  backdrop-filter: blur(10rpx);
}

.level-name {
  font-size: 28rpx;
  font-weight: bold;
}

.level-tip {
  font-size: 22rpx;
  margin-left: 10rpx;
  opacity: 0.8;
}

.level-commission {
  font-size: 24rpx;
  color: #22c55e;
  font-weight: 500;
  margin-top: 8rpx;
  display: block;
  text-align: center;
}

/* 新版等级徽章样式 - 优化设计 */
.level-badge-new {
  width: 90%;
  margin: 20rpx auto 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(255,255,255,0.85) 100%);
  border-radius: 24rpx;
  padding: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.08);
  backdrop-filter: blur(10rpx);
  border: 2rpx solid rgba(255,255,255,0.5);
}

.level-badge-content {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.level-info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.level-name-wrapper {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.level-icon {
  font-size: 36rpx;
}

.level-name-new {
  font-size: 32rpx;
  font-weight: bold;
  color: #4a7c59;
  letter-spacing: 1rpx;
}

.commission-badge {
  background: linear-gradient(135deg, #4a7c59 0%, #5a8c69 100%);
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(74, 124, 89, 0.3);
}

.commission-rate-new {
  font-size: 24rpx;
  font-weight: bold;
  color: #ffffff;
}

.level-points-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12rpx;
  border-top: 1rpx solid rgba(74, 124, 89, 0.1);
}

.points-text {
  font-size: 26rpx;
  color: #666;
}

.view-benefits-text {
  font-size: 24rpx;
  color: #4a7c59;
  font-weight: 500;
}

.progress-section {
  width: 100%;
  margin-top: 30rpx;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15rpx;
}

.current-points, .next-level-info {
  font-size: 24rpx;
  opacity: 0.9;
}

.progress-bar-wrapper {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.progress-bar {
  flex: 1;
  height: 8rpx;
  background-color: rgba(255,255,255,0.3);
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: white;
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.progress-percent {
  font-size: 22rpx;
  font-weight: bold;
  min-width: 60rpx;
}

.commission-section {
  display: flex;
  justify-content: space-around;
  background-color: white;
  padding: 40rpx 20rpx;
  margin: 20rpx;
  border-radius: 15rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
  position: relative;
  z-index: 2;
}

.commission-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.value {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.label {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

/* 旧版按钮样式（保留以防兼容） */
.button-group {
  display: flex;
  gap: 20rpx;
  padding: 0 20rpx;
  margin-bottom: 20rpx;
}

.withdraw-button {
  flex: 1;
  background-color: #ef4444;
  color: white;
  border-radius: 25rpx;
  height: 90rpx;
  font-size: 32rpx;
  position: relative;
  z-index: 2;
}

.withdraw-button[disabled] {
  background-color: #d1d5db;
  color: #9ca3af;
}

.query-button {
  flex: 1;
  background-color: #3b82f6;
  color: white;
  border-radius: 25rpx;
  height: 90rpx;
  font-size: 32rpx;
  position: relative;
  z-index: 2;
}

/* 新版提现按钮样式 - 优化设计 */
.withdraw-button-container {
  padding: 0 20rpx;
  margin-bottom: 20rpx;
}

.withdraw-button-new {
  width: 100%;
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: white;
  border-radius: 28rpx;
  height: 100rpx;
  font-size: 32rpx;
  position: relative;
  z-index: 2;
  box-shadow: 0 8rpx 24rpx rgba(239, 68, 68, 0.35);
  border: none;
  overflow: hidden;
}

.withdraw-button-new::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
  transition: left 0.5s;
}

.withdraw-button-new:active::before {
  left: 100%;
}

.withdraw-button-new[disabled] {
  background: linear-gradient(135deg, #d1d5db 0%, #9ca3af 100%);
  color: #6b7280;
  box-shadow: none;
}

.withdraw-button-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.withdraw-icon {
  font-size: 40rpx;
}

.withdraw-text {
  font-size: 32rpx;
  font-weight: bold;
  letter-spacing: 2rpx;
}

.withdraw-amount {
  font-size: 28rpx;
  font-weight: 600;
  margin-left: 8rpx;
  padding: 4rpx 12rpx;
  background-color: rgba(255,255,255,0.2);
  border-radius: 12rpx;
}

.admin-button {
  margin: 0 20rpx 20rpx;
  background-color: #6b7280;
  color: white;
  border-radius: 25rpx;
  position: relative;
  z-index: 2;
}

.orders-section {
  background-color: white;
  margin: 20rpx;
  padding: 30rpx;
  position: relative;
  z-index: 2;
  border-radius: 15rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25rpx;
    gap: 20rpx;
}

.tab-bar {
    display: flex;
    gap: 20rpx;
    flex: 1;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.tab-item {
    font-size: 26rpx;
    color: #666;
    padding-bottom: 10rpx;
    border-bottom: 2px solid transparent;
    transition: all 0.2s ease;
    white-space: nowrap;
    flex-shrink: 0;
}

.tab-item.active {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    border-bottom-color: #22c55e;
}

/* 刷新按钮 - 简洁风格 */
.refresh-button {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6rpx;
    padding: 10rpx 20rpx;
    background-color: #f0fdf4;
    color: #16a34a;
    border-radius: 30rpx;
    border: 1px solid #bbf7d0;
    font-size: 24rpx;
    transition: all 0.2s ease;
    flex-shrink: 0;
}

.refresh-button:active {
    background-color: #dcfce7;
    transform: scale(0.98);
}

.refresh-button.disabled {
    opacity: 0.5;
    pointer-events: none;
}

.refresh-icon {
    font-size: 28rpx;
    font-weight: bold;
    line-height: 1;
    display: inline-block;
}

.refresh-text {
    font-size: 24rpx;
    line-height: 1;
    font-weight: 500;
}

.refresh-icon.rotating {
    animation: rotate 1s linear infinite;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

.sync-button {
    font-size: 24rpx !important;
    padding: 10rpx 20rpx !important;
    margin: 0 !important;
    background-color: #f0f0f0 !important;
    color: #333 !important;
}

.order-date {
    font-size: 24rpx;
    color: #999;
}

.order-card {
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.order-card:last-child {
  border-bottom: none;
}

.order-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.order-id {
  font-size: 26rpx;
  color: #999;
}

.order-status {
  font-size: 28rpx;
  font-weight: bold;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
}

.order-status.unpaid {
  color: #6b7280;
  background-color: #f3f4f6;
}

.order-status.paid {
  color: #f59e0b;
  background-color: #fef3c7;
}

.order-status.shipped {
  color: #3b82f6;
  background-color: #dbeafe;
}

.order-status.completed {
  color: #22c55e;
  background-color: #dcfce7;
}

.order-status.cancelled {
  color: #9ca3af;
  background-color: #f9fafb;
}

.order-status.refunded {
  color: #ef4444;
  background-color: #fee2e2;
}

.order-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28rpx;
}

/* 返利信息样式 */
.commission-info {
  margin-top: 20rpx;
  padding: 20rpx;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 12rpx;
  border: 1rpx solid #bae6fd;
}

.commission-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.commission-row:last-child {
  margin-bottom: 0;
}

.commission-label {
  font-size: 26rpx;
  color: #64748b;
  font-weight: 500;
}

.commission-amount {
  font-size: 32rpx;
  font-weight: bold;
  color: #4a7c59;
}

.commission-status-tag {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-weight: 500;
}

/* 返利状态样式 */
.commission-status-tag.status-pending {
  color: #f59e0b;
  background-color: #fef3c7;
  border: 1rpx solid #fcd34d;
}

.commission-status-tag.status-activated {
  color: #22c55e;
  background-color: #dcfce7;
  border: 1rpx solid #86efac;
}

.commission-status-tag.status-cancelled {
  color: #ef4444;
  background-color: #fee2e2;
  border: 1rpx solid #fca5a5;
}

.commission-status-tag.status-none,
.commission-status-tag.status-unknown {
  color: #9ca3af;
  background-color: #f3f4f6;
  border: 1rpx solid #d1d5db;
}

/* 激活倒计时样式 */
.activation-countdown {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 12rpx;
  padding: 12rpx;
  background-color: #fff;
  border-radius: 8rpx;
  border: 1rpx dashed #0284c7;
}

.countdown-icon {
  font-size: 28rpx;
  margin-right: 8rpx;
}

.countdown-text {
  font-size: 24rpx;
  color: #0284c7;
  font-weight: 500;
}

.confirm-button {
  background-color: #3b82f6 !important;
  color: white !important;
  font-size: 24rpx !important;
  padding: 8rpx 16rpx !important;
  border-radius: 15rpx !important;
}

.empty-orders {
  text-align: center;
  color: #999;
  padding: 60rpx;
}

/* Level Modal Styles */
.level-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-content {
  background-color: white;
  padding: 40rpx;
  border-radius: 25rpx;
  width: 85%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  display: block;
  margin-bottom: 30rpx;
  color: #333;
}

.guidance-section {
  background-color: #f8fafc;
  padding: 25rpx;
  border-radius: 15rpx;
  margin-bottom: 30rpx;
}

.guidance-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #374151;
  display: block;
  margin-bottom: 15rpx;
}

.guidance-text {
  font-size: 26rpx;
  color: #6b7280;
  line-height: 1.5;
}

.level-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.level-item {
  background-color: #f9fafb;
  padding: 25rpx;
  border-radius: 15rpx;
  border: 2rpx solid transparent;
}

.level-item.active {
  background-color: #ecfdf5;
  border-color: #22c55e;
}

.level-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.level-name-modal {
  font-size: 30rpx;
  font-weight: bold;
  color: #1f2937;
}

.level-status {
  font-size: 22rpx;
  color: #22c55e;
  background-color: #dcfce7;
  padding: 4rpx 12rpx;
  border-radius: 10rpx;
}

.level-requirements {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.points-range, .commission-rate {
  font-size: 26rpx;
  color: #6b7280;
}

.special-benefit {
  font-size: 24rpx;
  color: #dc2626;
  background-color: #fee2e2;
  padding: 8rpx 12rpx;
  border-radius: 8rpx;
}

.close-button {
  margin-top: 40rpx;
  background-color: #22c55e;
  color: white;
  border-radius: 25rpx;
  height: 90rpx;
  font-size: 32rpx;
}

/* Withdraw Modal Styles */
.withdraw-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.withdraw-modal-content {
  background-color: white;
  padding: 40rpx;
  border-radius: 25rpx;
  width: 85%;
  max-height: 80vh;
  overflow-y: auto;
}

.withdraw-modal-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  display: block;
  margin-bottom: 15rpx;
  color: #333;
}

.withdraw-modal-subtitle {
  font-size: 28rpx;
  text-align: center;
  display: block;
  margin-bottom: 30rpx;
  color: #ef4444;
  font-weight: bold;
}

.withdraw-input-group {
  margin-bottom: 25rpx;
}

.withdraw-label {
  font-size: 28rpx;
  color: #333;
  display: block;
  margin-bottom: 15rpx;
  font-weight: bold;
}

.withdraw-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f9fafb;
  border: 2rpx solid #e5e7eb;
  border-radius: 12rpx;
  padding: 0 15rpx;
  margin-bottom: 12rpx;
}

.currency-symbol {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-right: 8rpx;
}

.withdraw-input {
  flex: 1;
  height: 80rpx;
  font-size: 32rpx;
  color: #333;
  background-color: transparent;
  border: none;
  outline: none;
}

.withdraw-input::placeholder {
  color: #d1d5db;
}

.withdraw-tips {
  font-size: 24rpx;
  color: #999;
  display: block;
  text-align: center;
}

.withdraw-error {
  background-color: #fee2e2;
  border: 1rpx solid #fecaca;
  border-radius: 12rpx;
  padding: 15rpx;
  margin-bottom: 25rpx;
}

.withdraw-error text {
  font-size: 26rpx;
  color: #dc2626;
  display: block;
  text-align: center;
}

.withdraw-button-group {
  display: flex;
  gap: 15rpx;
  margin-top: 30rpx;
}

.withdraw-cancel-button {
  flex: 1;
  background-color: #e5e7eb;
  color: #333;
  border-radius: 12rpx;
  height: 80rpx;
  font-size: 28rpx;
}

.withdraw-confirm-button {
  flex: 1;
  background-color: #ef4444;
  color: white;
  border-radius: 12rpx;
  height: 80rpx;
  font-size: 28rpx;
}

/* My Sharing Tab Styles */
.sharing-content {
  padding: 0;
}

.sharing-summary {
  display: flex;
  justify-content: space-around;
  background: linear-gradient(135deg, #f8fdf8 0%, #ffffff 100%);
  padding: 30rpx 20rpx;
  margin: 20rpx 0;
  border-radius: 15rpx;
  border: 1rpx solid #e8f5e8;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.summary-number {
  font-size: 36rpx;
  font-weight: bold;
  color: #22c55e;
  margin-bottom: 8rpx;
}

.summary-label {
  font-size: 24rpx;
  color: #666;
}

.empty-sharing {
  text-align: center;
  padding: 80rpx 40rpx;
  color: #999;
}

.empty-sharing text:first-child {
  display: block;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.empty-tip {
  font-size: 24rpx;
  color: #bbb;
  line-height: 1.5;
}

/* Points Detail Tab Styles */
.points-content {
  padding: 0;
}

.points-summary {
  padding: 20rpx 0;
}

.summary-card {
  background: linear-gradient(135deg, #4a7c59 0%, #5a8c69 100%);
  padding: 40rpx;
  margin: 0 20rpx;
  border-radius: 20rpx;
  text-align: center;
  box-shadow: 0 8rpx 24rpx rgba(74, 124, 89, 0.25);
}

.summary-title {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 12rpx;
  display: block;
}

.summary-value {
  font-size: 56rpx;
  font-weight: bold;
  color: #ffffff;
  display: block;
}

.empty-points {
  text-align: center;
  padding: 100rpx 40rpx;
  color: #999;
}

.empty-icon {
  font-size: 80rpx;
  display: block;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 12rpx;
}

.points-list {
  padding: 20rpx;
}

.point-record-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-left {
  display: flex;
  align-items: center;
  flex: 1;
  gap: 16rpx;
}

.record-icon {
  font-size: 40rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 12rpx;
}

.record-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  flex: 1;
}

.record-description {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.record-time {
  font-size: 24rpx;
  color: #999;
}

.record-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8rpx;
}

.record-amount {
  font-size: 32rpx;
  font-weight: bold;
}

.record-amount.positive {
  color: #22c55e;
}

.record-amount.negative {
  color: #ef4444;
}

.record-balance {
  font-size: 24rpx;
  color: #999;
}

.load-more {
  text-align: center;
  padding: 30rpx;
  color: #4a7c59;
  cursor: pointer;
}

.load-more-text {
  font-size: 28rpx;
}

.no-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
}

.no-more-text {
  font-size: 24rpx;
}

.sharing-list {
  padding: 0;
}

.sharing-card {
  display: flex;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.2s ease;
}

.sharing-card:active {
  background-color: #f8f8f8;
}

.sharing-card:last-child {
  border-bottom: none;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  margin-right: 20rpx;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f0f0f0;
}

.user-avatar image {
  width: 100%;
  height: 100%;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.user-nickname {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.user-register-time {
  font-size: 24rpx;
  color: #999;
}

.user-status {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-top: 5rpx;
}

.status-tag {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-weight: 500;
}

.status-tag.purchased {
  color: #22c55e;
  background-color: #dcfce7;
}

.status-tag.not-purchased {
  color: #999;
  background-color: #f5f5f5;
}

.commission-tag {
  font-size: 22rpx;
  color: #f59e0b;
  background-color: #fef3c7;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-weight: 500;
}
</style>
